﻿#ifndef RTPSEND_H
#define RTPSEND_H

#include <QThread>
#include <QUdpSocket>
#include <QTcpSocket>
#include <QMutexLocker>
#include <list>
#include "../comm/rtp.h"
#include "../comm/ffmpegheader.h"

//十六进制字节数组转十进制长度值
int32_t hexArrayToDec(char *array, int len);


enum AVPacketType
{
    //区分音视频以及是否带有起始字符
    PacketAudio = 0,
    PacketVideo,
    PacketAudioStart,
    PacketVideoStart
};

//待发送的RTP包
struct ReadyPacket
{
    AVPacketType type;
    AVPacket *packet;
};


//Rtp发送线程，负责发送AAC音频、H264视频的RTP包
class RtpPacketSender : public QThread
{
    Q_OBJECT
public:
    explicit RtpPacketSender(QString* ip);
    ~RtpPacketSender();

    void setRunState(bool start);

    //设置传输类型
    void setTransType(bool real);

    //rtp音视频时间戳
    void getRTPVideoTimeStamp(int64_t pts);
    void getRTPAudioTimeStamp(int64_t pts);

    //设置sps pps信息
    void setSPS_PPS(char *spsFrame, int spsLen, char *ppsFrame, int ppsLen);

    //释放队列
    void release();
    //音、视频包的写入
    void writePacket(ReadyPacket *packet);

    //解析H264组包RTP发送
    void parseH264PacketData(RtpPacket *rtpPacket, char *packetData, int packetSize, int64_t pts = 0);
    void parseH264PacketDataWithStartCode(RtpPacket *rtpPacket, char *packetData, int packetSize, int64_t pts = 0);
    void sendRtpH264Frame(RtpPacket *rtpPacket, char *frame, int frameSize, int64_t pts = 0);
    int  sendH264OverUDP(RtpPacket *rtpPacket, int packetSize);

    //解析AAC组包RTP发送
    void parseAACPacketData(RtpPacket *rtpPacket, char *packetData, int packetSize, int64_t pts = 0);
    void sendRtpAACFrame(RtpPacket *rtpPacket, char *frame, int frameSize, int64_t pts = 0);
    int  sendAACOverUDP(RtpPacket *rtpPacket, int packetSize);

protected:
    void run();

public:
    //媒体信息
    RTPMediaInfo info;

    //是否已设置
    bool setVideo;
    bool setAudio;

private:
    volatile bool isRun;

    QString *destIP; //指向外部SenderWidget的QString destIP

    //如果I帧前有sps pps，下面则可以不设置
    bool spsppsSet;
    char *spsFrame; int spsLen;
    char *ppsFrame; int ppsLen;

    //表示实时传输，恒为true
    bool isReal;

    //RTP包的时间戳
    uint32_t videoTimeStamp;
    uint32_t audioTimeStamp;

    //udp网络套接字
    QUdpSocket *videoSocket;
    QUdpSocket *audioSocket;

    //待发送的音视频包队列及其互斥锁，其实就是生产消费模型的缓冲区
    //消费者是RtpPacketSender线程函数，生产者是VideoCapturer和AudioCapturer线程
    QList<ReadyPacket *> packetList;
    QMutex mutex;
};







#endif // RTPSEND_H
